package org.uam.common;

import java.security.MessageDigest;

/**
 * 
 * MD5生成类
 * 
 * @author  Leo
 * @version  [版本号, 2012-11-16]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class MD5
{
    
    private static final String[] HEXDIGITS =
        {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    
    /**
     * <默认构造函数>
     */
    public MD5()
    {
    }
    
    /*
    public static void main(String args[])
    {
        System.out.print(encode("2"));
    }
    */

    /**
     * <一句话功能简述>
     * <功能详细描述>
     * @param b b
     * @return String
     * @see [类、类#方法、类#成员]
     */
    public static String byteArrayToHexString(byte b[])
    {
        StringBuffer resultSb = new StringBuffer();
        for (int i = ConstantsUtil.NUMBER_00; i < b.length; i++)
        {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }
    
    private static String byteToHexString(byte b)
    {
        int n = b;
        if (n < 0)
        {
            n += ConstantsUtil.NUMBER_256;
        }
        int d1 = n / ConstantsUtil.NUMBER_16;
        int d2 = n % ConstantsUtil.NUMBER_16;
        return (new StringBuilder(String.valueOf(HEXDIGITS[d1]))).append(HEXDIGITS[d2]).toString();
    }
    
    /**
     * <一句话功能简述>
     * <功能详细描述>
     * @param origin origin
     * @return String
     * @see [类、类#方法、类#成员]
     */
    public static String encode(String origin)
    {
        String resultString = null;
        try
        {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        return resultString;
    }
    
    /**
     * <一句话功能简述>
     * <功能详细描述>
     * @param origin origin
     * @return String
     * @see [类、类#方法、类#成员]
     */
    public static String encode(byte origin[])
    {
        String resultString = null;
        try
        {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(origin));
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        return resultString;
    }
}
